package com.jiankangjin.pay.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.jiankangjin.common.json.jackson.JSONUtil;
import com.jiankangjin.common.props.PropertiesUtil;
import com.jiankangjin.encryptKit.EncryptUtil;
import com.jiankangjin.encryptKit.RSAKey;
import com.jiankangjin.encryptKit.SignUtil;
import com.jiankangjin.httpclient.HttpClient;
import com.jiankangjin.pay.object.Merchant;
import com.jiankangjin.pay.services.MerchantPayServices;
import com.jiankangjin.pay.services.MerchantServices;
import com.jiankangjin.pay.services.ProductServices;
import com.jiankangjin.pay.util.StringUtil;
/**
 * 微信支付网关处理(微信公众号支付v3版)
 */

@Controller
@RequestMapping("/wx")
public class WxPayController {
	private static final Logger logger = Logger.getLogger(WxPayController.class);
	private static final String SYSTEMNAME = "[微信支付网关]";
	@Autowired 
	private MerchantPayServices  merchantPayServices;
	
	@Autowired
	private ProductServices productServices;
	
	@Autowired
	private MerchantServices merchantServices;
	
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/pay")
    public ModelAndView pay(HttpServletRequest request, 
    		HttpServletResponse response,
            @RequestParam(required = false) String inputcharset,
            @RequestParam(required = false) String version,
            @RequestParam(required = false) String language,
            @RequestParam(required = false) String signtype,
            @RequestParam(required = false) String pid,
            @RequestParam(required = false) String transactionid,
            @RequestParam(required = false) String orderamount,
            @RequestParam(required = false) String productinfo,
            @RequestParam(required = false) String channeltype,
            @RequestParam(required = false) String channelid,
            @RequestParam(required = false) String usertype,
            @RequestParam(required = false) String userid,
            @RequestParam(required = false) String ext1,
            @RequestParam(required = false) String ext2,
            @RequestParam(required = false) String pageurl,
            @RequestParam(required = false) String bgurl,
            @RequestParam(required = false) String signmsg
    ){
		logger.info(SYSTEMNAME+"微信支付请求开始====================");
		logger.info(SYSTEMNAME+"请求参数为:" +"inputcharset="+inputcharset+"version="+version+
				"language="+language+"signtype="+signtype+"pid="+pid+"transactionid="+transactionid+
				"orderamount="+orderamount+"productinfo="+productinfo+
				"channeltype="+channeltype+"channelid="+channelid+"usertype="+usertype+"userid="+
				userid+"ext1="+ext1+"ext2"+ext2+"pageurl="+pageurl+"bgurl="+bgurl+"signmsg="+signmsg);
		
    	//错误消息
    	String errorMsg = "";
    	
    	/**
    	 * 协议参数验证
    	 */
        if (!"1".equalsIgnoreCase(inputcharset)) {
        	errorMsg = "协议参数字符集错误";
            return getErrorModel(errorMsg);
        }

        if (!"v1.0".equalsIgnoreCase(version)) {
        	errorMsg = "协议参数网关版本错误";
        	return getErrorModel(errorMsg);
        }

        if (!"1".equalsIgnoreCase(language)) {
        	errorMsg = "协议参数语言种类错误";
        	return getErrorModel(errorMsg);
        }
        if (!"1".equalsIgnoreCase(signtype)) {
        	errorMsg = "协议参数签名类型错误";
        	return getErrorModel(errorMsg);
        }
        
        /**
         * 业务参数验证
         */
        if (StringUtil.isEmpty(pid)||pid.length()>20) {
        	errorMsg = "业务参数商户id格式不正确";
        	return getErrorModel(errorMsg);
		}
        if (!StringUtil.isTradeId(transactionid)||transactionid.length()>40) {
        	errorMsg = "医院订单号格式不正确";
        	return getErrorModel(errorMsg);
		}
        if (!StringUtil.isAmount(orderamount)) {
        	errorMsg = "订单金额格式不正确";
        	return getErrorModel(errorMsg);
		}
        /*if (!StringUtil.IsDateTimeString(ordertime)) {
        	errorMsg = "订单提交时间格式不正确";
        	return getErrorModel(errorMsg);
        }*/
        if (!"WXPUB".equalsIgnoreCase(channeltype)) {
        	errorMsg = "渠道类型不正确";
        	return getErrorModel(errorMsg);
        }
        if (StringUtil.isEmpty(channelid)) {
        	errorMsg = "渠道标识不能为空";
        	return getErrorModel(errorMsg);
        }
        //扩展字段不为空时再判断长度
        if (StringUtil.isNotEmpty(ext1)&&ext1.length()>200) {
        	errorMsg = "用户备注1过长";
        	return getErrorModel(errorMsg);
		}
        if (StringUtil.isNotEmpty(ext2)&&ext2.length()>200) {
        	errorMsg = "用户备注2过长";
        	return getErrorModel(errorMsg);
		}
        if (!StringUtil.IsURL(pageurl)) {
        	errorMsg = "页面跳转通知地址格式不正确";
        	return getErrorModel(errorMsg);
        }
        if (!StringUtil.IsURL(bgurl)) {
        	errorMsg = "服务器后台通知地址格式不正确";
        	return getErrorModel(errorMsg);
        }
        if (StringUtil.isEmpty(signmsg)) {
        	errorMsg = "签名字段不能为空";
        	return getErrorModel(errorMsg);
        }
        
        //查询商户信息
        Merchant merchant = merchantServices.byMerchant(pid);
	    //查询商户编号是否存在
	    if (merchant == null) {
	    	errorMsg = "商户编号不存在，不能支付";
	        return getErrorModel(errorMsg);
	    }
        //组装验签参数
        Map<String, String> map = new HashMap<String, String>();
        map.put("inputcharset", inputcharset);
        map.put("version", version);
        map.put("language", language);
        map.put("signtype", signtype);
        map.put("pid", pid);
        map.put("transactionid", transactionid);
        map.put("orderamount", orderamount);
        map.put("productinfo", productinfo);
        map.put("channeltype", channeltype);
        map.put("channelid", channelid);
        map.put("usertype", usertype);
        map.put("userid", userid);
        map.put("ext1", ext1);
        map.put("ext2", ext2);
        map.put("bgurl", bgurl);
        map.put("pageurl", pageurl);
       
        //签名验证
        String signKey = merchant.getMerchantSummaryKey();
        String privateKey = merchant.getMerchantPrivateDecrypt();
        Map<String,String> signMap = SignUtil.paraFilter(map);
        String str1 = SignUtil.createLinkString(signMap, "&");
        str1 = str1 + "&key=" + signKey;
        String signStr = EncryptUtil.sha(str1);

       /* if (!signStr.equalsIgnoreCase(signmsg)) {
            errorMsg = "签名数据不正确";
            return getErrorModel(errorMsg);
        }*/
//        String productStr="{\"productNumber\": \"5015648794166\", \"productName\": \"中华保健品\","
//				+ "\"productSpecifications\":\"1*20\",\"productNum\": \"2\", \"productPrice\": \"28.00\"}";
        
       // {[{productid:"5015648794166",productname="中华保健品",productspec="1*20",productquantity:2,productprice:28.00}]}
       // String productStr = "[{\"productid\":\"5015648794166\",\"productname\":\"中华保健品\",\"productspec\":\"1*20\",\"productquantity\":\"2\",\"productprice\":\"28.00\"},{\"productid\":\"5015648794166\",\"productname\":\"中华保健品\",\"productspec\":\"1*20\",\"productquantity\":\"2\",\"productprice\":\"28.00\"}]";
        String productStr = "";
       
//        try {
//			productStr = new String(EncryptUtil.encryptByPublicKey(EncryptUtil.hex2b(productinfo), merchant.getMerchantPublicDecrypt()));
//		} catch (Exception e1) {
//			logger.error(message, e1);
//		}
        
        /**
         * 解密商品明细
         */
        List<Map<String,String>> productMaps = new ArrayList<Map<String,String>>();//商品明细
        if(StringUtil.isNotEmpty(productinfo)){
        	byte[] productData = null;
            try {
                productData = EncryptUtil.dByPrivateKey(EncryptUtil.hex2b(productinfo), privateKey);
                if (productData == null){
                    errorMsg =  "商品明细不能解析";
                    return getErrorModel(errorMsg);
                }
                productStr = new String(productData, "UTF-8");
                //productStr用Json数据解析
                productMaps = JSONUtil.fromJSON(productStr, List.class);
            } catch (UnsupportedEncodingException e) {
            	errorMsg = "商品明细解密异常";
                logger.error(SYSTEMNAME+errorMsg, e);
                return getErrorModel(errorMsg);
                
            }
        }
        
        List<Map<String, Object>> goods = new ArrayList<Map<String, Object>>();//组装发给交易系统的商品明细
        
        for (Map<String, String> productMap : productMaps) {
            String productPrice=productMap.get("productprice");
            Map<String, Object> goodMap = new HashMap<String,Object>(); 
            goodMap.put("goods_type", "01");
            goodMap.put("goods_id", productMap.get("productid"));
            goodMap.put("goods_name", productMap.get("productname"));
            goodMap.put("std", productMap.get("productspec"));
            goodMap.put("goods_quantity", productMap.get("productquantity"));
            long productAmt = StringUtil.yuan2Fen(productPrice);
            goodMap.put("goods_price", productAmt);
            goods.add(goodMap);
            
		}
        // 查询订单号是否存在
       /* if (merchantPayServices.checkOrder(transactionid)){
            ModelAndView model = new ModelAndView("error");
            model.addObject("errMsg", "订单存在，不能重复支付");
            return model;
        }*/
        //组装请求交易系统创建订单数据
        Map<String,Object> orderMap = new HashMap<String,Object>();
        orderMap.put("module_id","111111" );
        orderMap.put("version", "1");
        orderMap.put("sign", "111111");
        orderMap.put("merchant_order_id",transactionid );
        orderMap.put("merchant_id", pid);
        orderMap.put("total_fee", StringUtil.yuan2Fen(orderamount));
        orderMap.put("currency", "156");
        orderMap.put("content", "11111");
        orderMap.put("goods_count", 1);
        orderMap.put("goods_detail", JSONUtil.toJSON(goods));
        orderMap.put("is_tip", "true");
        orderMap.put("buyer_name", "");
        orderMap.put("buyer_cellphone", "15111111111");
        orderMap.put("page_callback", "");
        orderMap.put("order_callback", bgurl);
        orderMap.put("page_callback", pageurl);
        //TODO 与交易系统通信之间的签名
        
        //请求交易系统创建订单
        logger.info(SYSTEMNAME+"请求交易系统创建订单参数："+orderMap);
        Map<String, Object> resultMap = HttpClient.getInstance().doPOSTgetHashMap("/transSystem/create_order",orderMap);
        //取出map的值，准备返回
  		if(resultMap == null || resultMap.size()<=0) {
             errorMsg = "请求交易系统创建订单请求失败";
             return getErrorModel(errorMsg);
  		}
        logger.info(SYSTEMNAME+"请求交易系统创建订单响应参数："+resultMap);
        //TODO 与交易系统通信之间的验签
  		String resp_status = (String)resultMap.get("resp_status");
  		String order_id = (String)resultMap.get("order_id");
  		if(!"0000".equalsIgnoreCase(resp_status)){
             errorMsg = "交易系统创建订单失败";
             return getErrorModel(errorMsg);
  		}
  		if(StringUtil.isEmpty(order_id)){
  			errorMsg = "交易系统创建订单失败";
            return getErrorModel(errorMsg);
  		}
  		String channelStr = (String)resultMap.get("channel");//获取返回渠道信息
  		if(StringUtil.isEmpty(channelStr)) {
  			errorMsg = "该商户没有配置支付渠道";
            return getErrorModel(errorMsg);
  		}
  		List<Map<String,String>> channels = JSONUtil.fromJSON(channelStr, List.class);
			if(channels==null||channels.size()<=0){
		}
		//String spbill_create_ip = getIpAddr(request);
		ModelAndView model = new ModelAndView("wx/oauth");
		String appid = "wxcec8863ae602c67c";
		
		Properties properties = PropertiesUtil.getInstance().loadByFilename("source");
		String wx_redirect_url = properties.getProperty("wx_redirect_url");
		//String redirect_url = "http://payment-test.jiankangjin.com/jkj-paygate/wx/doPay?order_id="+order_id+"&orderamount="+orderamount+"&channelid="+channelid+"&channeltype="+channeltype;
		String redirect_url = wx_redirect_url+"?order_id="+order_id+"&orderamount="+orderamount+"&channelid="+channelid+"&channeltype="+channeltype;
		try {
			redirect_url =  URLEncoder.encode(redirect_url, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return getErrorModel("回调地址编码异常");
		}
		String state = "123";
		String wx_authorize = properties.getProperty("wx_authorize");
		//String oauthurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+redirect_url+"&response_type=code&scope=snsapi_base&state="+state+"#wechat_redirect";
		//微信授权url
		String oauthurl = wx_authorize+"?appid="+appid+"&redirect_uri="+redirect_url+"&response_type=code&scope=snsapi_base&state="+state+"#wechat_redirect";
		//oauthurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxcec8863ae602c67c&redirect_uri=http://payment-test.jiankangjin.com/jkj-paygate/page/keyTest.action&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
		logger.debug("微信授权url："+oauthurl);
		model.addObject("oauthurl", oauthurl);
		return model;
		
  		
	}
	
	
	/**
	 * 微信授权重定向调用
	 * 请求交易系统支付
	 * 组装微信公众号支付需要的报文
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/doPay")
    public ModelAndView doPay(@RequestParam(required = false) String code,
    		@RequestParam(required = false) String order_id,
    		@RequestParam(required = false) String orderamount,
    		@RequestParam(required = false) String channelid,
    		@RequestParam(required = false) String channeltype,
    		@RequestParam(required = false) String spbill_create_ip,
    						  @RequestParam(required = false) String state,
    						  HttpServletRequest request){
		logger.info("微信授权返回参数:code="+code+"order_id="+order_id+"orderamount="+orderamount+"channelid="+channelid+
				"channeltype="+channeltype+"spbill_create_ip="+spbill_create_ip+"state="+state);
		spbill_create_ip = getIpAddr(request);
		System.out.println("ip------"+spbill_create_ip);
		String errorMsg = "";
		//请求微信通过code获取openid
		Map<String,Object> reqInfoMap = new HashMap<String,Object>();
		String appid = "wxcec8863ae602c67c";
		String secret = "701f0114d3ee3ebf972f162bafbc42f9";
		reqInfoMap.put("appid", appid);
		reqInfoMap.put("secret", secret);
		reqInfoMap.put("code", code);
		reqInfoMap.put("grant_type", "authorization_code");
		Properties properties = PropertiesUtil.getInstance().loadByFilename("source");
		String wx_token = properties.getProperty("wx_token");
		logger.info(SYSTEMNAME+"微信获取openid请求参数："+reqInfoMap);
		Map<String, Object> repInfoMap = HttpClient.getInstance().doPOSTgetHashMap(wx_token,reqInfoMap);
		logger.info(SYSTEMNAME+"微信获取openid返回参数："+repInfoMap);
		if(null==repInfoMap||repInfoMap.size()<=0){
			return getErrorModel("获取openid失败");
		}
		String openid = (String)repInfoMap.get("openid");
		if(StringUtil.isEmpty(openid)){
			return getErrorModel("获取openid失败");
		}
		//订单支付
		Map<String,Object> payMap = new HashMap<String,Object>();
		payMap.put("module_id", "111111");
		payMap.put("version", "11");
		payMap.put("sign", "111");
		payMap.put("local_pay_ssn", "11");
		payMap.put("order_id", order_id);
		payMap.put("fee", StringUtil.yuan2Fen(orderamount));
		payMap.put("currency", "156");
		payMap.put("channel_id", channelid);
		payMap.put("buyer_token", "11");
		payMap.put("buyer_voucher", "11");
		payMap.put("channel_type", channeltype);
		//自定义参数传到交易系统
		Map<String, Object> customMap = new HashMap<String, Object>();
		customMap.put("spbill_create_ip", spbill_create_ip); //订单生成的机器IP，指用户浏览器端IP
		customMap.put("orderamount", orderamount);
		customMap.put("openid", openid);
		customMap.put("trade_type", "JSAPI");
		
		payMap.put("custom_str", JSONUtil.toJSON(customMap, HashMap.class));
		//TODO 与交易系统通信之间的签名
		//请求交易系统支付
		logger.info(SYSTEMNAME+"请求交易系统订单支付接口参数："+payMap);
		Map<String, Object> resultPayMap = HttpClient.getInstance().doPOSTgetHashMap("/transSystem/pay_order", payMap);
		if(resultPayMap==null){
			errorMsg = "请求交易系统订单支付接口失败";
			return getErrorModel(errorMsg);
		}
		logger.info(SYSTEMNAME+"请求交易系统订单支付接口响应："+resultPayMap);
		
		String resp_status1 = (String)resultPayMap.get("resp_status");
	    String sub_deal_ssn = (String)resultPayMap.get("sub_deal_ssn");
	    String sub_deal_status = (String)resultPayMap.get("sub_deal_status");
//			    String sign = (String)resultPayMap.get("sign");
	    //TODO 与交易系统通信之间的验签
		if(!"0000".equalsIgnoreCase(resp_status1)||"0041".equalsIgnoreCase(sub_deal_status)){
            errorMsg = "请求交易系统订单支付失败";
            return getErrorModel(errorMsg);
 		}
	    
		//交易系统返回自定义参数
	    String return_custom_str = (String)resultPayMap.get("custom_str");
		Map<String, String> return_customMap = JSONUtil.fromJSON(return_custom_str, HashMap.class); 
        ModelAndView model = new ModelAndView("wx/order1");
        model.addObject("transactionid",sub_deal_ssn);
        model.addObject("orderamount",orderamount);
        model.addObject("channeltype",channeltype);
        model.addObject("channelid",channelid);
        model.addObject("name", "testtest");
        model.addAllObjects(return_customMap);
		return model;
		

		
	}
	
	/**
	 * 查询交易系统订单状态
	 * 跳转到商户通知页面
	 * @return
	 */
	@RequestMapping(value = "/toMer")
    public ModelAndView toMer(@RequestParam(required = false) String sub_deal_ssn ){
		logger.info(SYSTEMNAME+"sub_deal_ssn="+sub_deal_ssn);
		//查询交易系统订单状态
		Map<String,Object> reqMap = new HashMap<String,Object>();
		reqMap.put("module_id", "111111");
		reqMap.put("version", "v0.4");
		reqMap.put("sub_deal_ssn", sub_deal_ssn);
		reqMap.put("order_id", "");
		//TODO 签名
		reqMap.put("sign", "sign");
		Map<String, Object> repMap = HttpClient.getInstance().doPOSTgetHashMap("/transSystem/get_pay_status", reqMap);
		if(null==repMap||repMap.size()<=0){
			return getErrorModel("系统内部错误");
		}
		
		//跳转到商户通知页面
		String pid = (String)repMap.get("mer_id");
		
		//通知商户地址
//		String pageurl = "http://192.168.4.76:8080/jkj-paygate/page/keyTest.action";
		String pageurl = (String)repMap.get("page_url");
		//组装要返回给商户的参数
		Map<String,String> notiMap = new HashMap<String,String>();
		notiMap.put("pid", pid);
		notiMap.put("transactionid", (String)repMap.get("out_order_id"));
		notiMap.put("orderamount", (String)repMap.get("order_amount"));
		notiMap.put("dealid", (String)repMap.get("deal_id"));
		notiMap.put("channeltype", (String)repMap.get("pay_type"));
		notiMap.put("channeldealid", (String)repMap.get("bank_deal_id"));
		notiMap.put("dealtime", (String)repMap.get("deal_time"));
		notiMap.put("ext1", (String)repMap.get("ext1"));
		notiMap.put("ext2", (String)repMap.get("ext2"));
		notiMap.put("payresult", (String)repMap.get("pay_status"));
		notiMap.put("resultdesc", (String)repMap.get("pay_status_msg"));
		
		 //查询商户信息
        Merchant merchant = merchantServices.byMerchant(pid);
	    //查询商户编号是否存在
	    if (merchant == null) {
	        return getErrorModel("商户编号不存在，不能支付");
	    }
	    
	    String signKey = merchant.getMerchantSummaryKey();
		//签名
		Map<String,String> signMap = SignUtil.paraFilter(notiMap);
        String str1 = SignUtil.createLinkString(signMap, "&");
        str1 = str1 + "&key=" + signKey;
        logger.debug(SYSTEMNAME+"前台通知商户待签名串："+str1);
        String signmsg = EncryptUtil.sha(str1);
        
        logger.debug(SYSTEMNAME+"前台通知商户签名串："+signmsg);
		notiMap.put("signmsg", signmsg);
		logger.info(SYSTEMNAME+"返回给商户的参数为："+notiMap);
		
		ModelAndView model = new ModelAndView("wx/tomer");
		model.addObject("responseMap", notiMap);
		model.addObject("page_url", pageurl);
		return model;
		
	}
	
	
	
	
	public static void main(String[] args) {
//		String productStr="{\"productNumber\": \"5015648794166\", \"productName\": \"中华保健品\","
//				+ "\"productSpecifications\":\"1*20\",\"productNum\": \"2\", \"productPrice\": \"28.00\"}";
//		String productStr="[{\"productid\":\"5015648794166\",\"productname\":\"中华保健品\",\"productspec\":\"1*20\",\"productquantity\":\"2\",\"productprice\":\"28.00\"},{\"productid\":\"5015648794166\",\"productname\":\"中华保健品\",\"productspec\":\"1*20\",\"productquantity\":\"2\",\"productprice\":\"28.00\"}]";
//		String productStr="[]";
//		List<Map<String,String>> map1 = JSONUtil.fromJSON(productStr, List.class);
//		System.out.println(map1.size());
//		for (Map<String, String> map : map1) {
//			System.out.println(map);
//		}
		
		
//		List<Product> list = new ArrayList<Product>();
//		Product product=new Product();
//        product.setProductNumber("11");
//        product.setProductName("111");
//        product.setProductSpecifications("11");
//        product.setProductNum("111");
//        product.setProductPrice("11"); 
//        Product product1=new Product();
//        product1.setProductNumber("11");
//        product1.setProductName("111");
//        product1.setProductSpecifications("11");
//        product1.setProductNum("111");
//        product1.setProductPrice("11");
//        list.add(product);
//        list.add(product1);
//        System.out.println(JSONUtil.toJSON(list));hh0
		String productStr = "[{\"productid\":\"5015648794166\",\"productname\":\"中华保健品\",\"productspec\":\"1*20\",\"productquantity\":\"2\",\"productprice\":\"28.00\"},{\"productid\":\"5015648794166\",\"productname\":\"中华保健品\",\"productspec\":\"1*20\",\"productquantity\":\"2\",\"productprice\":\"28.00\"}]";
//		String productStr = "s";
		System.out.println("加密前"+productStr);
		System.out.println(productStr.length());
//		String ss = new String(productStr);
		try {
			RSAKey rSAKey = EncryptUtil.generateKey();
			byte[] s = null;
			try {
//				s = EncryptUtil.encryptByPublicKey1(productStr.getBytes(), rSAKey.hexPublicKey());
				s = EncryptUtil.encryptByPublicKey(productStr.getBytes(), "30819F300D06092A864886F70D010101050003818D0030818902818100A26FE1B3CE5C31447DB1A58C10B0DD1ECDECCF1CA63258373EED534C077796166E1A378A97B1352148C8B40957B25AF59301C43EEDA3B337F9B054B0078F51F90EA04BEA23343FA02F5174A669B0409F11A5CF293572B7CF57CEFDCAC54A33F06BAFFDE0CF3F340C26AA0E04178D0130544BAF21A78F9827A019CE35F7C5D7CF0203010001");
				String pro = EncryptUtil.b2Hex(s);
				System.out.println("加密后"+pro);
//				s = EncryptUtil.decryptByPrivateKey1(EncryptUtil.hex2b(pro), rSAKey.hexPrivateKey());
				s = EncryptUtil.dByPrivateKey(EncryptUtil.hex2b(pro), "30820276020100300D06092A864886F70D0101010500048202603082025C02010002818100A26FE1B3CE5C31447DB1A58C10B0DD1ECDECCF1CA63258373EED534C077796166E1A378A97B1352148C8B40957B25AF59301C43EEDA3B337F9B054B0078F51F90EA04BEA23343FA02F5174A669B0409F11A5CF293572B7CF57CEFDCAC54A33F06BAFFDE0CF3F340C26AA0E04178D0130544BAF21A78F9827A019CE35F7C5D7CF02030100010281803AEA4D7883CE58683916A7AEA7971E7C3FC0365673C92AC9CEDF112930442581B929751FA5693695FDEA1DB28DC638CB7D2854DF661DCBB0EFB50EE251BB9FC5198DAFA6337FEA73A38292B73F4706338C90E0B92DA42CBBA0CEA32D8F7D236D1D45A5BF6E8C86A2038BB78517AC8D8BB215A22DFA192FFE5C92FBD4E5BFE031024100F141890D105024472E0F77944C07E57E40D8760BEDEACBAFA8E346AC0E3E091BDB0186AD12C2E27262F7F84F92A522879F36C1D72167535C092789C93AF0050D024100AC5D380A82A3565990BB575303E4A6BF83258FA1820FB9FB38AFA9A24B51D6ABFA0BB8C76E62070BB533C924E697A47FBE22BB2697BE24305E37BA874CF8914B024100C5D332394716201949D89EFA383A0561B874869F93908342DFDEB575A21C164604184541A7EFABD595F7B56232623C652F15AC6EE6521E958A602468A06E6E050240125ADEF3E7938347886D1AD08152A11B35D913218CDB25E005DA57032C682BA726BA86D3DE025C63B7C92AFB5DFEFA0A8C71E0622CB897DBFABC8E858801D45F0240514D8477FEAD09555BE523B3F482A136C16A85A07D8E48C8F68CA1A55C2124594E03C6B99C17B31C5E6D5CC7ED93BCBC0C2AF1B8DC0C52F6472EFFE9258FB103");
				String pro1 = new String(s,"utf-8");
				System.out.println("解密后"+pro1);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		
		
	}
	/**
	 * 根据处理错误信息
	 * 打印日志
	 * 组建model对象
	 * @param errorMsg 错误信息
	 * @return model
	 */
	public ModelAndView getErrorModel(String errorMsg){
		errorMsg = SYSTEMNAME+errorMsg;
    	logger.error(errorMsg);
    	ModelAndView model = new ModelAndView("wx/error");
    	model.addObject("errMsg", errorMsg);
    	return model;
		
	}
	/**
	 * 获取ip
	 * @param request
	 * @return
	 */
	public String getIpAddr(HttpServletRequest request) {
	       String ip = request.getHeader("x-forwarded-for");
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	           ip = request.getHeader("Proxy-Client-IP");
	       }
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	           ip = request.getHeader("WL-Proxy-Client-IP");
	       }
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	           ip = request.getRemoteAddr();
	       }
	       return ip;
	   } 
	
}
